//
//  HLGiftContainerView.m
//  YueYue
//
//  Created by hulu001 on 2023/6/2.
//

#import "HLGiftContainerView.h"
#import <JXCategoryView/JXCategoryView.h>
#import "HLRtcCallKit.h"
#import "HLGiftCollectionView.h"
#import "HLGiftSendRequest.h"
#import "HLWalletRequest.h"
#import "HLRtcRechargeView.h"

@interface HLGiftContainerView ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong) NSArray *menus;
@property (nonatomic, strong) HLGiftCollectionView *giftCollectionView;
@property (nonatomic, strong) HLGiftCollectionView *bagCollectionView;
@property (nonatomic, strong) QMUIButton *sendButton;
@property (nonatomic, strong) UIImageView *coinView;
@property (nonatomic, strong) UILabel *amountLabel;
@property (nonatomic, strong) QMUIButton *rechargeButton;
@property (nonatomic, assign) HLGiftListType giftType;
@property (nonatomic, assign) HLGiftPlaceType placeType;
@property (nonatomic, strong) HLUserInfoModel *toUser;
@property (nonatomic, copy) HLCommonCallback callback;
@property (nonatomic, copy) HLCommonCallbackBoolBlock closeCallback;
@end

@implementation HLGiftContainerView

- (instancetype)initWithFrame:(CGRect)frame placeType:(HLGiftPlaceType)placeType
{
    if (self = [super initWithFrame:frame]) {
        self.placeType = placeType;
        if (placeType == HLGiftPlaceTypeVideo || placeType == HLGiftPlaceTypeAudio){
            self.menus = @[@"礼物"];
        } else {
            self.menus = @[@"礼物", @"背包"];
        }
       
        [self setupView];
    }
    return self;
}



- (void)setupView
{
    self.backgroundColor = UIColor.whiteColor;
    self.layer.cornerRadius = 16;
    self.layer.masksToBounds = YES;
    self.bottomView = [[UIView alloc] init];
    _bottomView.backgroundColor = UIColor.whiteColor;
    [self addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(12);
    }];
    
    self.categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 34)];
    self.categoryView.delegate = self;
    self.categoryView.titleColor = [UIColor qmui_colorWithHexString:@"#A2A6B0"];
    self.categoryView.titleSelectedColor = [UIColor qmui_colorWithHexString:@"#1A1A1A"];
    self.categoryView.titleFont = UIFontMediumMake(16);
    self.categoryView.titleSelectedFont = UIFontMediumMake(18);
    self.categoryView.averageCellSpacingEnabled = NO;
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = YES;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.titleLabelStrokeWidthEnabled = YES;
    self.categoryView.contentEdgeInsetLeft = 20;
    self.categoryView.cellSpacing = 18;
    self.categoryView.backgroundColor = UIColor.whiteColor;
    self.categoryView.titles = self.menus;
    [self addSubview:self.categoryView];
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorColor = HLMainColor;
    lineView.indicatorHeight = 3.f;
    lineView.indicatorWidth = 6;
    lineView.indicatorCornerRadius = 1.5f;
    lineView.verticalMargin = 2;
    lineView.lineStyle = JXCategoryIndicatorLineStyle_Lengthen;
    self.categoryView.indicators = @[lineView];
    
    self.listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self addSubview:self.listContainerView];
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(_categoryView.mas_bottom).offset(0);
    }];
    // 关联到 categoryView
    self.categoryView.listContainer = self.listContainerView;
    
    self.sendButton = [[QMUIButton alloc] init];
    [_sendButton setTitle:@"赠送" forState:UIControlStateNormal];
    [_sendButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    _sendButton.titleLabel.font = UIFontMediumMake(12);
    _sendButton.cornerRadius = 14;
    _sendButton.backgroundColor = HLMainColor;
    _sendButton.contentEdgeInsets = UIEdgeInsetsMake(6, 12, 6, 12);
    [_sendButton addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_sendButton];
    [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.top.equalTo(_listContainerView.mas_bottom).offset(10);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 10));
    }];
    
    self.coinView = [[UIImageView alloc] initWithImage:UIImageMake(@"home_flow_coin")];
    [self addSubview:_coinView];
    [_coinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.centerY.equalTo(_sendButton);
    }];
    
    self.amountLabel = [[UILabel alloc] init];
    _amountLabel.textColor = [UIColor qmui_colorWithHexString:@"#191919"];
    _amountLabel.font = UIFontMediumMake(16);
    _amountLabel.text = @"0";
    [self addSubview:_amountLabel];
    [_amountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_coinView.mas_right).offset(8);
        make.centerY.equalTo(_coinView);
    }];
    
    self.rechargeButton =[QMUIButton.alloc init];
    [_rechargeButton setTitle:@"充值" forState:UIControlStateNormal];
    [_rechargeButton setTitleColor:HLMainColor forState:UIControlStateNormal];
    _rechargeButton.titleLabel.font = UIFontBoldMake(12);
    [_rechargeButton setImage:UIImageMake(@"mine_income_arrow") forState:UIControlStateNormal];
    _rechargeButton.imagePosition = QMUIButtonImagePositionRight;
    _rechargeButton.spacingBetweenImageAndTitle = 3;
    [self addSubview:_rechargeButton];
    [_rechargeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_amountLabel.mas_right).offset(16);
        make.centerY.equalTo(_amountLabel);
    }];
    
    [self walletAmountRequest];
}


- (void)sendAction
{
    NSDictionary *params = @{};
    HLGiftSendType sendType = HLGiftSendTypeUser;
    
    HLGiftCollectionView *giftView = self.giftCollectionView;
    if (self.giftType == HLGiftListTypeBag){
        giftView = self.bagCollectionView;
    }
    HLGiftModel *gift = giftView.changeModel;
    if (gift == nil){
        [QMUITips showWithText:@"请选择要发送的礼物!"];
        return;
    }
    
    if (self.giftType == HLGiftListTypeBag){
        sendType = HLGiftSendTypeBag;
        params = @{
            @"activeCode":gift.activeCode,
            @"activeGiftCode":gift.activeGiftCode,
            @"activeGiftQuantity":@"1",
            @"objectUser":_toUser.userId,
        };
    } else {
        switch (_placeType) {
            case HLGiftPlaceTypeUser:
                sendType = HLGiftSendTypeUser;
                params = @{
                    @"giftCode" : gift.giftCode,
                    @"objectUser" : _toUser.userId,
                    @"quantityCode" : @"1"};
                break;
            case HLGiftPlaceTypeIM:
                sendType = HLGiftSendTypeIM;
                params = @{
                    @"giftCode" : gift.giftCode,
                    @"objectUser" : _toUser.userId,
                    @"quantityCode" : @"1"};
                break;
            case HLGiftPlaceTypeVideo:
                sendType = HLGiftSendTypeVideo;
                params = @{
                    @"giftCode" : gift.giftCode,
                    @"objectUser" : _toUser.userId,
                    @"roomId" : HLRtcCallKit.sharedInstance.channelName};
                break;
            case HLGiftPlaceTypeAudio:
                sendType = HLGiftSendTypeAudio;
                params = @{
                    @"giftCode" : gift.giftCode,
                    @"objectUser" : _toUser.userId,
                    @"roomId" : HLRtcCallKit.sharedInstance.channelName};
                break;
                
            default:
                break;
        }
    }
    
    HLGiftSendRequest *sendRequest = [[HLGiftSendRequest alloc] initWithType:sendType params:params];
    [sendRequest startWithCompletionBlockWithSuccess:^(HLGiftSendRequest * _Nonnull request) {
        if (request.isSuccess){
            //[QMUITips showWithText:@"礼物发送成功"];
            if(self.callback){
                
                NSDictionary *params = @{@"gift":gift};
               NSString *userVideoDuration = [request userVideoDuration];
                if (userVideoDuration.length > 0){
                    params = @{@"gift":gift, @"userVideoDuration": userVideoDuration};
                }
                
                self.callback(params);
            }
            
            if (self.closeCallback){
                self.closeCallback(YES);
            }
        }
        
    } failure:nil];
}


- (void)walletAmountRequest
{
    HLWalletRequest *walletRequest = [[HLWalletRequest alloc] initWithType:HLWalletTypeBalance params:@{}];
    [walletRequest startWithCompletionBlockWithSuccess:^(__kindof HLWalletRequest * _Nonnull request) {
        if (request.isSuccess){
            self.amountLabel.text = [request balance];
        }
    } failure:nil];
}


- (void)giftCurrentWithIndex:(NSInteger)index
{
    if (index == 1){
        self.giftType = HLGiftListTypeBag;
    } else {
        self.giftType = HLGiftListTypeList;
    }
}

#pragma mark - JXCategoryViewDelegate

/**
 滚动选中的情况才会调用该方法

 @param categoryView categoryView对象
 @param index 选中的index
 */
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index
{
    
    [self giftCurrentWithIndex:index];
}

/**
 控制能否点击Item

 @param categoryView categoryView对象
 @param index 准备点击的index
 @return 能否点击
 */
- (BOOL)categoryView:(JXCategoryBaseView *)categoryView canClickItemAtIndex:(NSInteger)index
{
    [self giftCurrentWithIndex:index];
    return  YES;
}

// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.menus.count;
}
// 根据下标 index 返回对应遵守并实现 `JXCategoryListContentViewDelegate` 协议的列表实例
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 1){
        if (self.bagCollectionView == nil){
            self.bagCollectionView = [[HLGiftCollectionView alloc] initWithType:HLGiftListTypeBag];
        }
        self.giftType = HLGiftListTypeBag;
        return _bagCollectionView;
    } else {
        if (self.giftCollectionView == nil){
            self.giftCollectionView = [[HLGiftCollectionView alloc] initWithType:HLGiftListTypeList];
        }
        self.giftType = HLGiftListTypeList;
        return _giftCollectionView;
    }
}

+ (void)showWithPlaceType:(HLGiftPlaceType)type
                     user:(HLUserInfoModel *)user
                 callback:(HLCommonCallback)callback
{
    CGFloat height = 368;
    HLGiftContainerView *containerView = [[HLGiftContainerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height) placeType:type];
    containerView.toUser = user;
    containerView.callback = callback;
    QMUIModalPresentationViewController *modalViewController = [[QMUIModalPresentationViewController alloc] init];
    modalViewController.contentViewMargins = UIEdgeInsetsMake(SCREEN_HEIGHT-height, 0, 0, 0);
    modalViewController.contentView = containerView;
    modalViewController.dimmingView.backgroundColor = UIColorClear;
    [modalViewController showWithAnimated:YES completion:nil];
    
    [containerView.rechargeButton setQmui_tapBlock:^(__kindof UIControl *sender) {
        [modalViewController hideWithAnimated:NO completion:^(BOOL finished) {
            if (type == HLGiftPlaceTypeVideo){
                [HLRtcRechargeView show];
            } else {
                [HLUIHelper h5WithURL:HLH5IncomeUrl controller:[QMUIHelper visibleViewController]];
            }
        }];
    }];
    
    containerView.closeCallback = ^(BOOL confirm) {
        if (confirm){
            [modalViewController hideWithAnimated:YES completion:nil];
        }
    };
    
}

@end
